<template>
  <!-- 临时用电作业票申请 -->
  <view>
    <view class="form-container">
      <uni-forms ref="form" :modelValue="ticketForm" :rules="rules" labelPosition="top" label-width="70vw">
        <view class="hidden-title">信息填写</view>
        <cu-cell-group>
          <uni-forms-item name="workLocation">
            <cu-cell title="作业地点" column required>
              <uni-easyinput
                type="textarea"
                v-model="ticketForm.workLocation"
                placeholder="请输入作业地点(限20字)"
                maxlength="20"
              />
            </cu-cell>
          </uni-forms-item>
          <uni-forms-item name="powerAP">
            <cu-cell title="电源接入点" column required>
              <uni-easyinput
                type="textarea"
                v-model="ticketForm.powerAP"
                placeholder="请输入电源接入点(限20字)"
                maxlength="20"
              />
            </cu-cell>
          </uni-forms-item>
          <uni-forms-item name="libId">
            <hazardous-medium-select v-model="ticketForm.libId" label="危害介质" placeholder="请选择" required />
          </uni-forms-item>

          <uni-forms-item name="device">
            <cu-cell title="用电设备" column required>
              <uni-easyinput
                type="textarea"
                v-model="ticketForm.device"
                placeholder="请输入用电设备(限20字)"
                maxlength="20"
              />
            </cu-cell>
          </uni-forms-item>
        </cu-cell-group>

        <cu-cell-group class="bor-top">
          <uni-forms-item name="weight">
            <cu-cell title="许可用电功率(KW)" required>
              <input
                type="number"
                v-model="ticketForm.permissionPower"
                placeholder="请输入"
                class="input"
                placeholder-class="form-placeholder__style"
                maxlength="20"
              />
            </cu-cell>
          </uni-forms-item>
          <uni-forms-item name="workVoltage">
            <cu-cell title="工作电压(V)" required>
              <input
                type="number"
                v-model="ticketForm.workVoltage"
                placeholder="请输入"
                class="input"
                placeholder-class="form-placeholder__style"
                maxlength="20"
              />
            </cu-cell>
          </uni-forms-item>
          <uni-forms-item name="ratedPower">
            <cu-cell title="额定功率(KW)" required>
              <input
                type="number"
                v-model="ticketForm.ratedPower"
                placeholder="请输入"
                class="input"
                placeholder-class="form-placeholder__style"
                maxlength="20"
              />
            </cu-cell>
          </uni-forms-item>
        </cu-cell-group>

        <cu-cell-group class="bor-top">
          <uni-forms-item name="startTime">
            <uni-datetime-picker
              hide-second
              :start="now"
              :end="endTime"
              type="datetime"
              @change="onTimeChange($event, 'startTime')"
            >
              <cu-cell
                title="计划开始时间"
                required
                link
                placeholder="请选择"
                :description="ticketForm.startTime"
              ></cu-cell>
            </uni-datetime-picker>
          </uni-forms-item>
          <uni-forms-item name="endTime">
            <uni-datetime-picker
              hide-second
              :start="startTime"
              type="datetime"
              @change="onTimeChange($event, 'endTime')"
            >
              <cu-cell
                title="计划结束时间"
                required
                link
                placeholder="请选择"
                :description="ticketForm.endTime"
              ></cu-cell>
            </uni-datetime-picker>
          </uni-forms-item>
        </cu-cell-group>

        <cu-cell-group class="bor-top">
          <!--作业人电工证号-->
          <uni-forms-item name="workerLabel">
            <cu-cell
              title="接电作业人员（本企业/持电工证）"
              required
              link
              placeholder="请选择"
              :description="ticketForm.workerLabel"
              @click="showUserSelector('worker')"
            ></cu-cell>
            <uni-forms-item name="workCertificates" label="">
              <div
                v-for="(item, index) in ticketForm.workCertificates"
                :key="index"
                style="display: inline-flex; justify-content: space-between; align-items: center; width: 95%"
              >
                <div class="index">{{ index + 1 }}</div>
                <div class="name">{{ item.name }}</div>
                <div class="content">
                  <cu-cell
                    title=""
                    link
                    placeholder="请选择"
                    :description="item.qualityName"
                    @click="selectCertificate(item.quality)"
                  ></cu-cell>
                </div>
                <div class="operate">
                  <span @click="removeCertificates(index)">移除</span>
                </div>
              </div>
            </uni-forms-item>
          </uni-forms-item>

          <!--作业负责人电工证号-->
          <uni-forms-item name="commanderLabel">
            <cu-cell
              title="接电作业负责人（本企业/持电工证）"
              required
              link
              placeholder="请选择"
              :description="ticketForm.commanderLabel"
              @click="showUserSelector('commander')"
            ></cu-cell>
            <uni-forms-item name="workCertificates" label="">
              <div
                v-for="(item, index) in ticketForm.workPrincipalCertificates"
                :key="index"
                style="display: inline-flex; justify-content: space-between; align-items: center; width: 95%"
              >
                <div class="index">{{ index + 1 }}</div>
                <div class="name">{{ item.name }}</div>
                <div class="content">
                  <cu-cell
                    title=""
                    link
                    placeholder="请选择"
                    :description="item.qualityName"
                    @click="selectCommanderCertificate(item.quality)"
                  ></cu-cell>
                </div>
                <div class="operate">
                  <span @click="removeCommanderCertificates(index)">移除</span>
                </div>
              </div>
            </uni-forms-item>
          </uni-forms-item>
        </cu-cell-group>
      </uni-forms>

      <!--电工作业人员证书-->
      <data-picker
        ref="qualityRef"
        title=""
        label-key="qualityName"
        value-key="qualityId"
        :data="qualities"
        @confirm="qualityConfirm"
      ></data-picker>

      <!--电工指挥人员证书-->
      <data-picker
        ref="qualityCommanderRef"
        title=""
        label-key="qualityName"
        value-key="qualityId"
        :data="commanderQualities"
        @confirm="qualityCommanderConfirm"
      ></data-picker>
    </view>

    <!-- 用户选择器 v2 -->
    <cu-dept-user-select
      ref="deptUserSelectRef"
      :checkList="deptUserSelectProps.checkList"
      :multiple="deptUserSelectProps.multiple"
      @change="onDeptUserChange"
    ></cu-dept-user-select>
  </view>
</template>

<script>
import CuCellGroup from '@/components/cu-cell/cu-cell-group.vue'
import CuCell from '@/components/cu-cell/cu-cell.vue'
import CuSelect from '@/components/cu-select/cu-select.vue'
import DictPicker from '@/components/dict-picker/index.vue'
import DataPicker from '@/components/data-picker/index.vue'
import dayjs from 'dayjs'
import { getGasLibs, getQualificationInfo } from '../../../api/spw/ticketApply'
import CuDeptUserSelect from '@/components/cu-dept-user-select/cu-dept-user-select.vue'
import { cloneDeep } from 'lodash'
import HazardousMediumSelect from '@/components/hazardous-medium-select/hazardous-medium-select.vue'

export default {
  components: {
    HazardousMediumSelect,
    CuDeptUserSelect,
    CuCellGroup,
    CuCell,
    CuSelect,
    DictPicker,
    DataPicker
  },
  props: {
    ticketInfo: {
      type: Object,
      default: () => {}
    },
    templateId: {
      type: [String, Number],
      default: ''
    },
    unitType: {
      type: [String, Number],
      default: ''
    }
  },
  data() {
    const validatorLib = (rule, value, data, callback) => {
      if (value.length) {
        return true
      } else {
        return callback('不能为空')
      }
    }
    return {
      deptUserSelectProps: {
        checkList: [],
        multiple: false
      },
      ticketForm: {
        libId: [], // 危害介质
        workLocation: '', // 作业地点
        powerAP: '', // 电源接入点
        permissionPower: '', // 许可用电功率
        workVoltage: '', // 工作电压
        device: '', // 用电设备
        ratedPower: '', // 额定功率
        startTime: '',
        endTime: '',
        workerId: '',
        workerLabel: '',
        workCertificates: [],
        commanderId: '', // 指挥人
        commanderLabel: '', // 指挥人名字
        workPrincipalCertificates: []
      },
      selectUserType: 1,
      nodeIdx: '',
      result: {},
      qualities: [],
      commanderQualities: [],
      staffs: [],
      now: dayjs(new Date()).format('YYYY-MM-DD HH:mm'),
      rules: {
        libId: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            },
            {
              validateFunction: validatorLib
            }
          ]
        },
        workLocation: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        startTime: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        endTime: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        powerAP: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        permissionPower: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        workVoltage: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        device: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        ratedPower: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        workerLabel: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        commanderLabel: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        }
      }
    }
  },
  computed: {
    endTime() {
      if (!this.ticketForm.endTime) {
        return ''
      }
      return dayjs(this.ticketForm.endTime).valueOf() - 60 * 60 * 1000
    },
    startTime() {
      if (!this.ticketForm.startTime) {
        return ''
      }
      return dayjs(this.ticketForm.startTime).valueOf() + 60 * 60 * 1000
    }
  },
  watch: {
    ticketInfo: {
      async handler(val) {
        if (val) {
          Object.keys(this.ticketInfo).map((k) => {
            this.ticketForm[k] = cloneDeep(this.ticketInfo[k])
          })
        }
      },
      immediate: true
    }
  },

  methods: {
    onDeptUserChange(val) {
      if (!val) {
        return
      }
      switch (this.selectUserType) {
        // 接电作业人
        case 'worker':
        // 接电负责人
        case 'commander':
          this.electricUserConfirm(val)
          break
        default:
          break
      }
    },
    async electricUserConfirm(obj) {
      const request = []
      obj.forEach((item) => {
        request.push(getQualificationInfo(item.userId))
      })
      const res = await Promise.all(request)
      obj.map((item, index) => {
        item.quality = res[index].data
        if (!item.quality.length) return
        item.quality.map((q) => {
          q.text = q.qualityName
          q.value = q.qualityId
        })

        // 默认选中第一个证书
        item.qualityName = item.quality[0].qualityName
        item.qualityId = item.quality[0].qualityId
        item.qualityNumber = item.quality[0].qualityNumber
      })

      if (this.selectUserType === 'worker') {
        this.ticketForm.workCertificates = obj
        this.ticketForm.workerLabel = '已确认'
      } else if (this.selectUserType === 'commander') {
        this.ticketForm.workPrincipalCertificates = obj
        this.ticketForm.commanderLabel = '已确认'
      }
    },

    /*作业人电工证号列表操作*/
    selectCertificate(data) {
      this.qualities = data
      this.$refs.qualityRef.open()
    },
    qualityConfirm(obj) {
      let idx = this.ticketForm.workCertificates.findIndex((c) => {
        return c.userId === obj.userId
      })

      let quality = JSON.parse(JSON.stringify(this.ticketForm.workCertificates[idx].quality))
      let updateObj = {
        name: obj.userName,
        userId: obj.userId,
        qualityName: obj.qualityName,
        qualityId: obj.qualityId,
        qualityNumber: obj.qualityNumber,
        quality: quality
      }
      this.$set(this.ticketForm.workCertificates, idx, updateObj)
    },
    removeCertificates(idx) {
      this.ticketForm.workCertificates.splice(idx, 1)
      if (!this.ticketForm.workCertificates.length) this.ticketForm.workerLabel = ''
    },

    /*作业负责人电工证号列表操作*/
    selectCommanderCertificate(data) {
      this.commanderQualities = data
      this.$refs.qualityCommanderRef.open()
    },
    qualityCommanderConfirm(obj) {
      let idx = this.ticketForm.workPrincipalCertificates.findIndex((c) => {
        return c.userId === obj.userId
      })

      let quality = JSON.parse(JSON.stringify(this.ticketForm.workPrincipalCertificates[idx].quality))
      let updateObj = {
        name: obj.userName,
        userId: obj.userId,
        qualityName: obj.qualityName,
        qualityId: obj.qualityId,
        qualityNumber: obj.qualityNumber,
        quality: quality
      }
      this.$set(this.ticketForm.workPrincipalCertificates, idx, updateObj)
    },

    removeCommanderCertificates(idx) {
      this.ticketForm.workPrincipalCertificates.splice(idx, 1)
      if (!this.ticketForm.workPrincipalCertificates.length) this.ticketForm.commanderLabel = ''
    },

    showUserSelector(type) {
      this.selectUserType = type
      switch (type) {
        // 接电作业人
        case 'worker':
          this.deptUserSelectProps.checkList = []
          this.deptUserSelectProps.multiple = true
          break
        // 接电负责人
        case 'commander':
          this.deptUserSelectProps.checkList = []
          this.deptUserSelectProps.multiple = true
          break
        default:
          break
      }
      this.$refs.deptUserSelectRef.open()
    },

    onTimeChange(val, key) {
      if (val.trim().includes(' ')) {
        this.ticketForm[key] = val.trim()
      } else {
        this.$modal.showToast('请选择日期和时间')
      }
    },

    // 作业人员证书校验
    validWorker() {
      if (!this.ticketForm.workCertificates.length) return

      return new Promise((resolve, reject) => {
        let b = this.ticketForm.workCertificates.some((ca) => {
          return ca.quality.length === 0
        })
        if (b) {
          this.$modal.showToast('请选择接电作业人员作业证')
          reject('qualityId is required')
        } else resolve(true)
      })
    },

    // 作业指挥人员证书校验
    validPrincipalPerson() {
      if (!this.ticketForm.workPrincipalCertificates.length) return

      return new Promise((resolve, reject) => {
        let b = this.ticketForm.workPrincipalCertificates.some((ca) => {
          return ca.quality.length === 0
        })
        if (b) {
          this.$modal.showToast('请选择接电作业负责人作业证')
          reject('qualityId is required')
        } else resolve(true)
      })
    },

    async submit() {
      await this.$refs.form.validate()
      await this.validWorker()
      await this.validPrincipalPerson()

      const start = dayjs(this.ticketForm.startTime).valueOf()
      const end = dayjs(this.ticketForm.endTime).valueOf()
      const oneHour = 60 * 60 * 1000
      if (end - start < oneHour) {
        this.$modal.showToast('开始时间与结束时间间隔必须大于60分钟')
        return
      }
      this.result = {
        ...this.ticketForm,
        procDefId: this.procDefId,
        workType: this.ticketForm.specialWorkType,
        workId: this.ticketForm.workId
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.lib-radio ::v-deep .cu-select-item {
  width: auto;
  margin: 0 10px;
}
.index {
  width: 15px;
}
.name {
  width: 15%;
}
.content {
  width: 60%;
}
</style>
